package org.jeecg.modules.car.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ComUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseFloor;
import org.jeecg.entity.basedata.BaseProject;
import org.jeecg.entity.basedata.BaseRoom;
import org.jeecg.entity.car.*;
import org.jeecg.enums.car.CarOrderTypeEnum;
import org.jeecg.enums.car.CarStatusEnum;
import org.jeecg.enums.car.CarSyncStatusEnum;
import org.jeecg.modules.car.entity.CarCheck;
import org.jeecg.modules.car.entity.CarExVo;
import org.jeecg.modules.car.entity.CarFeeRule;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.service.*;
import org.jeecg.modules.car.service.impl.ForeignCarJGSService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.vo.car.ForeignCarMonthlyRentReq;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 月卡车列表
 * @Author: jeecg-boot
 * @Date: 2019-07-10
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "月卡车列表")
@RestController
@RequestMapping("/b/car/carInfo")
public class CarInfoController {
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private ICarPortService carPortService;
    @Autowired
    private ICarParkInfoService carParkInfoService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ICarCheckService carCheckService;
    @Autowired
    private ICarModelService carModelService;
    @Autowired
    private ICarTypeService carTypeService;
    @Autowired
    private ICarFeeRuleService carFeeRuleService;
    @Autowired
    private ForeignCarJGSService foreignCarJGSService;
    @Autowired
    private ICarOrderService carOrderService;
    @Autowired
    private ICarInfoEditService carInfoEditService;


    /**
     * 分页列表查询
     *
     * @param carInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "月卡车列表-分页列表查询")
    @ApiOperation(value = "月卡车列表-分页列表查询", notes = "月卡车列表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CarInfo>> queryPageList(CarInfo carInfo,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        Result<IPage<CarInfo>> result = new Result<IPage<CarInfo>>();
        carInfo.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",carInfo.getMenuPath(),null,null));
        Page<CarInfo> page = new Page<CarInfo>(pageNo, pageSize);
        List<CarInfo> list = carInfoService.findPage(page,carInfo);
        for (CarInfo carRes:list){
           CarOrder carOrder =  carOrderService.getEndChargeTime(carRes.getId(), CarOrderTypeEnum.ORDER_TYPE_MONTHS.getCode());
           if (carOrder != null){
               carRes.setEndChargeTime(carOrder.getPayTime());
           }
            if (carRes.getLocalStartTime() != null && carRes.getLocalEndTime() != null){  //ab车状态
                if (carRes.getLocalEndTime().equals(carRes.getLocalStartTime())){
                    carRes.setAbStatus(0);
                } else {
                    carRes.setAbStatus(1);
                }
            }
           //固定车位车辆开始结束时间显示为车位时间
           if (StringUtils.isNotBlank(carRes.getCarPortId()) && carRes.getStatus().equals(CarStatusEnum.SYNC_STATUS_NORMAL.getCode())){
               carRes.setLocalStartTime(carRes.getPortLocalStartTime());
               carRes.setLocalEndTime(carRes.getPortLocalEndTime());
           }
        }
        page.setRecords(list);
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }

    /**
     * 审核分页列表查询
     *
     * @param carInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "月卡车列表-分页列表查询")
    @ApiOperation(value = "月卡车列表-分页列表查询", notes = "月卡车列表-分页列表查询")
    @GetMapping(value = "/checklist")
    public Result<IPage<CarInfo>> checklist(CarInfo carInfo,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<CarInfo>> result = new Result<IPage<CarInfo>>();
        carInfo.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",carInfo.getMenuPath(),null,carInfo.getDepartIdEx()));
        Page<CarInfo> page = new Page<CarInfo>(pageNo, pageSize);
        page.setRecords(carInfoService.findPage(page,carInfo));
        result.setSuccess(true);
        result.setResult(page);
        return result;
    }


    /**
     * 添加
     *
     * @param carInfo
     * @return
     */
    @AutoLog(value = "月卡车列表-添加")
    @ApiOperation(value = "月卡车列表-添加", notes = "月卡车列表-添加")
    @PostMapping(value = "/add")
    public Result<CarInfo> add(@RequestBody CarInfo carInfo) {
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            CarParkInfo parkInfo = carParkInfoService.getById(carInfo.getParkId());
            if (StringUtils.isEmpty(parkInfo.getOutSysId())){
                return Result.error("所属车场未配置线下车场,无法添加车辆！");
            }
            if (parkInfo.getIsCheckOpenCard() == false){
                carInfo.setCheckStatus(1);
            }
            if (StringUtils.isBlank(parkInfo.getProjectId())){
                carInfo.setProjectId(parkInfo.getProjectId());
            }
            if (!ComUtil.isPlateNumber(carInfo.getCarNo())){
                return Result.error("车牌号码输入不合法，请检查后再提交");
            }
            if (StringUtils.isBlank(carInfo.getCarNo()) || carInfo.getCarNo().trim().length() == 0){
                return Result.error("请输入车牌！");
            }
            carInfo.setCarNo(carInfo.getCarNo().trim());
            //判断是否存在
            CarInfo exist = carInfoService.getByCarNo(carInfo.getCarNo(), carInfo.getParkId());
            if (exist != null){
                return Result.error("车辆[" + carInfo.getCarNo() + "]系统已存在,请勿重复添加！");
            }
            if(StringUtils.isNotBlank(carInfo.getCarPortId())){
                List<CarInfo> infos = carInfoService.getByCarPortId(carInfo.getCarPortId());
                CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                if (infos.size() >= 1 && carPort.getIsAb() == 0){
                    return Result.error("当前车位已经绑定车辆["+infos.get(0).getCarNo()+"]且车位非AB车位无法再次绑定车辆！");
                }
                carInfo.setLocalStartTime(carPort.getLocalStartTime());
                carInfo.setLocalEndTime(carPort.getLocalEndTime());
                carInfo.setRoomId(carPort.getRoomId());
                carInfo.setFeeRuleId(null);
                carInfo.setRoomName(carPort.getRoomName());
                carInfo.setFloorId(carPort.getFloorId());
                carInfo.setFloorName(carPort.getFloorName());
                CarType carType = carTypeService.getById(carInfo.getCarType());
                if (carType == null){
                    return Result.error("车类不存在");
                }
                //固定月租车
                if(!carType.getName().contains("月租车")){
                    return Result.error("固定车位车辆车类必须为月租车");
                }
            }
            carInfoService.save(carInfo);
            return Result.ok("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 车牌停用
     * @param carId
     * @return
     */
    @AutoLog(value = "月卡车列表-车牌停用")
    @ApiOperation(value = "月卡车列表-车牌停用", notes = "月卡车列表-车牌停用")
    @GetMapping(value = "/startCar")
    public Result startCar(@RequestParam(name = "carId", required = true) String carId){
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(carId));
            if (carInfoList == null || carInfoList.size() == 0 ){
                return result.error500("未查询到当前车辆信息");
            }
            CarInfo carInfo = carInfoList.get(0);
            if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                List<CarInfo> infos = carInfoService.getByCarPortId(carInfo.getCarPortId());
                if (infos.size() >= 1 && carPort.getIsAb() == 0){
                    return Result.error("当前车位已经绑定车辆["+infos.get(0).getCarNo()+"]且车位非AB车位，车辆启用失败！");
                }
                //已经同步车辆 && 车位未删除
                if (carInfo.getSyncStatus().equals(CarSyncStatusEnum.SYNC_STATUS_YES.getCode())){
                    Result<String> syncRes = foreignCarJGSService.saveMonthlyRentUtils(carInfo, DateUtils.date2Str(carInfo.getLocalStartTime(),DateUtils.datetimeFormat), DateUtils.date2Str(carPort.getLocalEndTime(),DateUtils.datetimeFormat));
                    if(syncRes.isSuccess() == false){
                        return result.error500(syncRes.getMessage());
                    }
                }
                carInfo.setLocalEndTime(carPort.getLocalEndTime());
                carInfo.setStatus(CarStatusEnum.SYNC_STATUS_NORMAL.getCode());
                carInfoService.updateById(carInfo);
            }else {
                if (carInfo.getSyncStatus().equals(CarSyncStatusEnum.SYNC_STATUS_YES.getCode())){
                    Result<String> syncRes = foreignCarJGSService.saveMonthlyRentUtils(carInfo, DateUtils.date2Str(carInfo.getLocalStartTime(),DateUtils.datetimeFormat), DateUtils.date2Str(carInfo.getLocalEndTime(),DateUtils.datetimeFormat));
                    if(syncRes.isSuccess() == false){
                        return result.error500(syncRes.getMessage());
                    }
                }
                carInfo.setStatus(CarStatusEnum.SYNC_STATUS_NORMAL.getCode());
                carInfoService.updateById(carInfo);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作异常！");
        }
        return result;
    }


    /**
     * 车牌停用
     * @param carId
     * @return
     */
    @AutoLog(value = "月卡车列表-车牌停用")
    @ApiOperation(value = "月卡车列表-车牌停用", notes = "月卡车列表-车牌停用")
    @GetMapping(value = "/stopCar")
    public Result editCarNo(@RequestParam(name = "carId", required = true) String carId){
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(carId));
            if (carInfoList == null || carInfoList.size() == 0 ){
                return result.error500("未查询到当前车辆信息");
            }
            CarInfo carInfo = carInfoList.get(0);
            //已经同步车辆
            if (carInfo.getSyncStatus().equals(CarSyncStatusEnum.SYNC_STATUS_YES.getCode())){
                //删除车禁信息，不管车辆是否在不在场 todo 其他车辆是否要处理？？？
                ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                req.setPark_id(carInfo.getOutParkId());
                req.setPlate_number(carInfo.getCarNo());
                //删除车禁信息
                Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                if(syncRes.isSuccess() == false){
                    return result.error500(syncRes.getMessage());
                }
            }
            carInfo.setStatus(CarStatusEnum.SYNC_STATUS_STOP.getCode());
            carInfoService.updateById(carInfo);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作异常！");
        }
        return result;
    }

    /**
     * 修改车牌号
     * @param carNoOld
     * @param carNoNew
     * @return
     */
    @AutoLog(value = "月卡车列表-车牌修改")
    @ApiOperation(value = "月卡车列表-车牌修改", notes = "月卡车列表-车牌修改")
    @GetMapping(value = "/editCarNo")
    public Result editCarNo(@RequestParam(name = "carInfoId", required = true) String carInfoId,
                            @RequestParam(name = "carNoOld", required = true) String carNoOld,
                            @RequestParam(name = "carNoNew", required = true) String carNoNew, String remarks){
        carNoNew = carNoNew.replaceAll(" ", "");
        carNoOld = carNoOld.replaceAll(" ", "");
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            if (!ComUtil.isPlateNumber(carNoNew)){
                return Result.error("车牌号码格式错误，请检查后再提交");
            }
            List<String> list = new ArrayList<>();
            list.add(carInfoId);
            List<CarInfo> carInfoList = carInfoService.findByIds(list);
            if (carInfoList == null || carInfoList.size() == 0 ){
                return result.error500("未查询到当前车辆信息");
            }
            CarInfo carInfo = carInfoList.get(0);
            if (carInfo == null){
                return result.error500("未查询到当前车辆信息");
            }
            if (carNoOld.equals(carNoNew)){
                return result.error500("新车牌与修改车牌不能相同");
            }
            //todo 后续需要增加车场条件
            CarInfo exist = carInfoService.getByCarNo(carNoNew, carInfo.getParkId());
            if (exist != null){
                return result.error500("修改后的车牌在当前系统中已存在，请勿重复添加");
            }
            //判断车牌状态只有当  审核通过 &&  已经同步 && 启用状态的才去调用车禁
            if (carInfo.getCheckStatus() ==  IParkConstants.CHECK_STATUS_PASSED && carInfo.getSyncStatus().equals(CarSyncStatusEnum.SYNC_STATUS_YES.getCode()) && carInfo.getStatus().equals(CarStatusEnum.SYNC_STATUS_NORMAL.getCode())){
                //数据完整性校验
                if (!carInfo.getCarTypeName().contains("月租")){
                    return result.error500("非月租车,信息有误,同步终止！");
                }
                if (carInfo.getLocalStartTime() == null || carInfo.getLocalEndTime() == null){
                    return result.error500("月卡有效期不能为空！信息有误，同步终止！");
                }
                if (StringUtils.isBlank(carInfo.getOutParkId())){
                    return result.error500("所在车场未配置线下车场！信息有误，同步终止！");
                }
                ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                req.setPark_id(carInfo.getOutParkId());
                req.setPlate_number(carInfo.getCarNo());
                //删除车禁信息
                Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                if (syncRes.isSuccess()){
                    //车禁 添加
                    ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                    rentReq.setPark_id(carInfo.getOutParkId());
                    if (StringUtils.isNotBlank(carInfo.getOwnerName())){
                        rentReq.setEmp_name(carInfo.getOwnerName());
                    } else {
                        rentReq.setEmp_name(carInfo.getMobile());
                    }
                    rentReq.setEmp_moblie(carInfo.getMobile());
                    rentReq.setPlate_number(carNoNew);
                    rentReq.setCartypeid(carInfo.getOutCarType());
                    rentReq.setCarmodelid(carInfo.getOutCarModel());
                    rentReq.setBegindate(DateUtils.date2Str(carInfo.getLocalStartTime(),DateUtils.datetimeFormat));
                    rentReq.setEnddate(DateUtils.date2Str(carInfo.getLocalEndTime(),DateUtils.datetimeFormat));
                    //新增车禁信息
                    Result<String> syncResSave = foreignCarJGSService.saveMonthlyRent(rentReq);
                    //添加修改记录
                    CarInfoEdit carInfoEdit = new CarInfoEdit();
                    carInfoEdit.setCarNoOld(carNoOld);
                    carInfoEdit.setCarNoNew(carNoNew);
                    carInfoEdit.setParkId(carInfo.getParkId());
                    carInfoEdit.setProjectId(carInfo.getProjectId());
                    carInfoEdit.setCarInfoId(carInfo.getId());
                    carInfoEdit.setRemarks(remarks);
                    carInfoEditService.save(carInfoEdit);
                    if (syncResSave.isSuccess()){
                        //修改car_info车牌
                        carInfo.setCarNo(carNoNew);
                        carInfoService.updateById(carInfo);
                    } else {
                        //同步失败 - 修改车牌信息，并将同步状态改为未同步
                        carInfo.setCarNo(carNoNew);
                        carInfo.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                        carInfoService.updateById(carInfo);
                        result.setMessage("车牌修改成功，同步车禁失败");
                        result.setSuccess(false);
                        return result;
                    }
                }else {
                    result.setMessage(syncRes.getMessage());
                    result.setSuccess(false);
                    return result;
                }
            }else {
                //添加修改记录
                CarInfoEdit carInfoEdit = new CarInfoEdit();
                carInfoEdit.setCarNoOld(carNoOld);
                carInfoEdit.setCarNoNew(carNoNew);
                carInfoEdit.setParkId(carInfo.getParkId());
                carInfoEdit.setProjectId(carInfo.getProjectId());
                carInfoEdit.setCarInfoId(carInfo.getId());
                carInfoEdit.setRemarks(remarks);
                carInfoEditService.save(carInfoEdit);
                //修改car_info车牌
                carInfo.setCarNo(carNoNew);
                carInfoService.updateById(carInfo);
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作异常！");
        }
        return result;
    }


    /**
     * 月卡车列表-审核
     *
     * @param carInfo
     * @return
     */
    @AutoLog(value = "月卡车列表-审核")
    @ApiOperation(value = "月卡车列表-审核", notes = "月卡车列表-审核")
    @PutMapping(value = "/checkAccess")
    public Result<CarInfo> checkAccess(@RequestBody CarInfo carInfo) {
        Result<CarInfo> result = new Result<CarInfo>();
        Map<String, Object> map = null;
        //用户标识车位下是否有车辆已经同步
        boolean isSync = false;
        try {
            if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                List<CarInfo> carPortCarList = carInfoService.getByCarPortId(carInfo.getCarPortId());
                for (CarInfo i : carPortCarList){
                    if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(i.getSyncStatus())){
                        isSync = true;
                    }
                }
                //有车辆已经同步
                if (isSync){
                    carInfoService.updateCheckStatus(carInfo);
                    CarCheck carCheck = new CarCheck();
                    carCheck.setCarId(carInfo.getId());
                    carCheck.setCheckRes(carInfo.getCheckStatus());
                    carCheck.setCheckReason(carInfo.getCheckReason());
                    carCheck.setCheckUser(SsoUtil.getLoginUser().getId());
                    carCheckService.save(carCheck);
                    if (carInfo.getCarTypeName().contains("月租") &&
                        IParkConstants.CHECK_STATUS_PASSED == carInfo.getCheckStatus() &&
                        StringUtils.isBlank(carInfo.getOutParkId()) &&
                        carInfo.getLocalStartTime() != null && carInfo.getLocalEndTime() != null){
                        List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(carInfo.getId()));
                        ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                        rentReq.setPark_id(carInfoList.get(0).getOutParkId());
                        if (StringUtils.isNotBlank(carInfoList.get(0).getOwnerName())){
                            rentReq.setEmp_name(carInfoList.get(0).getOwnerName());
                        } else {
                            rentReq.setEmp_name(carInfoList.get(0).getMobile());
                        }
                        rentReq.setEmp_moblie(carInfoList.get(0).getMobile());
                        rentReq.setPlate_number(carInfoList.get(0).getCarNo());
                        rentReq.setCartypeid(carInfoList.get(0).getOutCarType());
                        rentReq.setCarmodelid(carInfoList.get(0).getOutCarModel());
                        rentReq.setBegindate(DateUtils.date2Str(carInfoList.get(0).getLocalStartTime(),DateUtils.datetimeFormat));
                        rentReq.setEnddate(DateUtils.date2Str(carInfoList.get(0).getLocalEndTime(),DateUtils.datetimeFormat));
                        Result<String> syncRes = foreignCarJGSService.saveMonthlyRent(rentReq);
                        if (syncRes.isSuccess()){
                            //更新同步状态
                            carInfoService.updateSyncStatus(carInfoList.get(0).getId());
                            return Result.ok("操作成功,并已自动同步车禁信息");
                        } else {
                            return Result.ok("审核成功，自动同步车禁失败！");
                        }
                    }
                }else{
                    carInfoService.updateCheckStatus(carInfo);
                    CarCheck carCheck = new CarCheck();
                    carCheck.setCarId(carInfo.getId());
                    carCheck.setCheckRes(carInfo.getCheckStatus());
                    carCheck.setCheckReason(carInfo.getCheckReason());
                    carCheck.setCheckUser(SsoUtil.getLoginUser().getId());
                    carCheckService.save(carCheck);
                    return Result.ok("操作成功");
                }
            }else {
                carInfoService.updateCheckStatus(carInfo);
                CarCheck carCheck = new CarCheck();
                carCheck.setCarId(carInfo.getId());
                carCheck.setCheckRes(carInfo.getCheckStatus());
                carCheck.setCheckReason(carInfo.getCheckReason());
                carCheck.setCheckUser(SsoUtil.getLoginUser().getId());
                carCheckService.save(carCheck);
                return Result.ok("操作成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param carInfo
     * @return
     */
    @AutoLog(value = "月卡车列表-编辑")
    @ApiOperation(value = "月卡车列表-编辑", notes = "月卡车列表-编辑")
    @PutMapping(value = "/edit")
    public Result<CarInfo> edit(@RequestBody CarInfo carInfo) {
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                CarType carType = carTypeService.getById(carInfo.getCarType());
                if (carType == null){
                    return Result.error("车类不存在");
                }
                //固定月租车
                if(!carType.getName().contains("月租车")){
                    return Result.error("固定车位车辆车类必须为月租车");
                }
            }
            List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(carInfo.getId()));
            if (carInfoList == null || carInfoList.size() == 0 ){
                return result.error500("未查询到当前车辆信息");
            }
            CarInfo carInfoEntity = carInfoList.get(0);
            //编辑时未修改车位
            if (StringUtils.isNotBlank(carInfoEntity.getCarPortId()) && carInfo.getCarPortId().equals(carInfoEntity.getCarPortId())){
                carInfo.setProjectId(carInfoEntity.getProjectId());
                boolean ok = carInfoService.updateById(carInfo);
                if (ok) {
                 return result.success("修改成功!");
                }
                //非固定车位车辆直接修改
            }else if (StringUtils.isBlank(carInfoEntity.getCarPortId()) || StringUtils.isBlank(carInfo.getCarPortId())){
                carInfo.setProjectId(carInfoEntity.getProjectId());
                boolean ok = carInfoService.updateById(carInfo);
                if (ok) {
                    return result.success("修改成功!");
                }
            }else {
                //获取车位信息
                CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                if (carPort == null){
                    return  result.error500("未找到对应车位信息");
                }
                carInfo.setLocalStartTime(carPort.getLocalStartTime());
                carInfo.setLocalEndTime(carPort.getLocalEndTime());
                //已经同步车辆
                if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(carInfoEntity.getSyncStatus())){
                    //新车场没有有效期  --- 删除车禁信息
                  if (carInfo.getLocalEndTime() == null || carInfo.getLocalStartTime() == null){
                      ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                      req.setPark_id(carInfoEntity.getOutParkId());
                      req.setPlate_number(carInfo.getCarNo());
                      //删除车禁信息
                      Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                      if (syncRes.isSuccess() == false){
                          return result.error500("删除车禁信息异常！");
                      }
                      //设置车辆未同步
                      carInfo.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                  }else {
                      //更新车禁信息
                      ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                      rentReq.setPark_id(carInfoEntity.getOutParkId());
                      if (StringUtils.isNotBlank(carInfo.getOwnerName())){
                          rentReq.setEmp_name(carInfo.getOwnerName());
                      } else {
                          rentReq.setEmp_name(carInfo.getMobile());
                      }
                      rentReq.setEmp_moblie(carInfo.getMobile());
                      rentReq.setPlate_number(carInfo.getCarNo());
                      rentReq.setCartypeid(carInfoEntity.getOutCarType());
                      rentReq.setCarmodelid(carInfoEntity.getOutCarModel());
                      rentReq.setBegindate(DateUtils.date2Str(carInfo.getLocalStartTime(),DateUtils.datetimeFormat));
                      rentReq.setEnddate(DateUtils.date2Str(carInfo.getLocalEndTime(),DateUtils.datetimeFormat));
                      //新增车禁信息
                      Result<String> syncResSave = foreignCarJGSService.saveMonthlyRent(rentReq);
                      if (syncResSave.isSuccess() == false){
                          return result.error500("添加车禁信息失败！");
                      }
                  }
                    carInfo.setProjectId(carInfoEntity.getProjectId());
                    carInfo.setRoomId(carPort.getRoomId());
                    carInfo.setFeeRuleId(null);
                    carInfo.setRoomName(carPort.getRoomName());
                    carInfo.setFloorId(carPort.getFloorId());
                    carInfo.setFloorName(carPort.getFloorName());
                    //固定月租车
                   // carInfo.setCarType("2428c100f656444d88ecb10bf0f9ebcd");
                    boolean ok = carInfoService.updateById(carInfo);
                    if (ok) {
                        return result.success("修改成功!");
                    }
                }else {
                    //未同步车辆
                    carInfo.setProjectId(carInfoEntity.getProjectId());
                    carInfo.setLocalStartTime(carPort.getLocalStartTime());
                    carInfo.setLocalEndTime(carPort.getLocalEndTime());
                    carInfo.setRoomId(carPort.getRoomId());
                    carInfo.setFeeRuleId(null);
                    carInfo.setRoomName(carPort.getRoomName());
                    carInfo.setFloorId(carPort.getFloorId());
                    carInfo.setFloorName(carPort.getFloorName());
                    //固定月租车
                    //carInfo.setCarType("2428c100f656444d88ecb10bf0f9ebcd");
                    boolean ok = carInfoService.updateById(carInfo);
                    if (ok) {
                        return result.success("修改成功!");
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("车辆编辑异常！");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "月卡车列表-通过id删除")
    @ApiOperation(value = "月卡车列表-通过id删除", notes = "月卡车列表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        Result<CarInfo> result = new Result<CarInfo>();
        try {
            List<String> list = new ArrayList<>();
            list.add(id);
            List<CarInfo> carInfoList = carInfoService.findByIds(list);
            if (carInfoList == null || carInfoList.size() == 0 ){
                return result.error500("未查询到当前车辆信息");
            }
            /*if(carInfoList.size() > 1){
                return result.error500("车辆["+ carInfoList.get(0).getCarNo() + "]在系统中存在重复数据，请删除不需要数据再操作。");
            }*/
            CarInfo carInfo = carInfoList.get(0);
            if (carInfo.getCheckStatus() ==  IParkConstants.CHECK_STATUS_PASSED && carInfo.getSyncStatus().equals(CarSyncStatusEnum.SYNC_STATUS_YES.getCode())){
                ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                req.setPark_id(carInfo.getOutParkId());
                req.setPlate_number(carInfo.getCarNo());
                Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                if (syncRes.isSuccess()){
                    carInfoService.removeById(id);
                } else {
                    result.setMessage(syncRes.getMessage());
                    result.setSuccess(false);
                    return result;
                }
            }else {
                carInfoService.removeById(id);
            }
        } catch (Exception e) {
            log.error("操作失败", e.getMessage());
            return Result.error("操作失败!");
        }
        return Result.ok("操作成功!");
    }

    @AutoLog(value = "根据车位id查询绑定的车辆")
    @ApiOperation(value = "根据车位id查询绑定的车辆", notes = "根据车位id查询绑定的车辆")
    @GetMapping(value = "/getCarNoByCarPortId")
    public Result<List<CarInfo>> getCarNoByCarPortId(@RequestParam(name = "carPortId", required = true) String carPortId) {
        Result result = new Result();
        List<CarInfo> carInfos = carInfoService.getByCarPortId(carPortId);
        result.setResult(carInfos);
        return result;

    }
    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "月卡车列表-批量删除")
    @ApiOperation(value = "月卡车列表-批量删除", notes = "月卡车列表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<CarInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<CarInfo> result = new Result<CarInfo>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.carInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }
 
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "月卡车列表-通过id查询")
    @ApiOperation(value = "月卡车列表-通过id查询", notes = "月卡车列表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CarInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<CarInfo> result = new Result<CarInfo>();
        CarInfo carInfo = carInfoService.getById(id);
        if (carInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(carInfo);
            result.setSuccess(true);
        }
        return result;
    }

    //同步月卡时间缺少23:59:59使用
    public  void xiugai(){
        List<CarInfo> list = carInfoService.findByIds();
        System.out.println(list.size());
        StringBuilder sb  = new StringBuilder();
        StringBuilder su = new StringBuilder();
        for (CarInfo carInfo: list){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(carInfo.getLocalEndTime());
            log.info("车牌："+carInfo.getCarNo() +"---修改前---"+ DateUtils.date2Str(carInfo.getLocalEndTime(), DateUtils.datetimeFormat));
            calendar.add(Calendar.HOUR, 23);
            calendar.add(Calendar.MINUTE, 59);
            calendar.add(Calendar.SECOND, 59);
            carInfo.setLocalEndTime(calendar.getTime());
            log.error("车牌："+carInfo.getCarNo() +"---修改后---"+ DateUtils.date2Str(calendar.getTime(), DateUtils.datetimeFormat));
            String ids = carInfo.getId();
            List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(ids.split(",")));
            if (carInfoList.size() <= 0){
                log.error("异常车辆id="+ carInfo.getId());
                continue;
            }
            CarInfo xiugai =  carInfoList.get(0);
            xiugai.setLocalEndTime(carInfo.getLocalEndTime());
            if (!(IParkConstants.CHECK_STATUS_PASSED == xiugai.getCheckStatus())){
                log.error(xiugai.getCarNo()+":车辆未审核通过，无法同步！");
                continue;
            }
            if (!xiugai.getCarTypeName().contains("月租")){
                log.error(xiugai.getCarNo()+":非月租车,同步终止！");
                continue;
            }
            if (xiugai.getLocalStartTime() == null || xiugai.getLocalEndTime() == null){
                log.error(xiugai.getCarNo()+":月卡有效期不能为空！");
                continue;
            }
            if (StringUtils.isBlank(xiugai.getOutParkId())){
                log.error(xiugai.getCarNo()+":所在车场未配置线下车场！");
                continue;
            }
            ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
            rentReq.setPark_id(xiugai.getOutParkId());
            if (StringUtils.isNotBlank(xiugai.getOwnerName())){
                rentReq.setEmp_name(xiugai.getOwnerName());
            } else {
                rentReq.setEmp_name(xiugai.getMobile());
            }
            rentReq.setEmp_moblie(xiugai.getMobile());
            rentReq.setPlate_number(xiugai.getCarNo());
            rentReq.setCartypeid(xiugai.getOutCarType());
            rentReq.setCarmodelid(xiugai.getOutCarModel());
            rentReq.setBegindate(DateUtils.date2Str(xiugai.getLocalStartTime(),DateUtils.datetimeFormat));
            rentReq.setEnddate(DateUtils.date2Str(xiugai.getLocalEndTime(),DateUtils.datetimeFormat));
            Result<String> syncRes = foreignCarJGSService.saveMonthlyRent(rentReq);
            if (syncRes.isSuccess()){
                carInfoService.updateById(carInfo);
                //更新同步状态
               // carInfoService.updateSyncStatus(xiugai.getId());
                log.info(xiugai.getCarNo()+"同步成功："+ xiugai.getCarNo()+"开始时间："+ DateUtils.date2Str(xiugai.getLocalStartTime(),DateUtils.datetimeFormat )+"结束时间："+DateUtils.date2Str(xiugai.getLocalEndTime(),DateUtils.datetimeFormat ));
              //  su.append(xiugai.getCarNo()).append(":").append(syncRes.getMessage());
            } else {
                log.error(xiugai.getCarNo()+"同步失败");
             //   sb.append(xiugai.getCarNo()).append(":").append(syncRes.getMessage());
            }
        }

    }

    @AutoLog(value = "月租车信息同步到车场")
    @ApiOperation(value = "月租车信息同步到车场", notes = "月租车信息同步到车场")
    @PostMapping(value = "/syncCarMonthToPark")
    public Result<String> syncCarMonthToPark(@RequestParam(name = "ids", required = true) String ids) {
        log.info("月租车信息同步到车场接受信息:{}",ids);
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别");
        }
        List<CarInfo> carInfoList = carInfoService.findByIds(Arrays.asList(ids.split(",")));
        StringBuilder sb  = new StringBuilder();
        StringBuilder su = new StringBuilder();
        for (CarInfo carInfo:carInfoList){
            if (!(IParkConstants.CHECK_STATUS_PASSED == carInfo.getCheckStatus())){
                sb.append(carInfo.getCarNo()).append(":车辆未审核通过，无法同步！");
                continue;
            }
            if (!carInfo.getCarTypeName().contains("月租")){
                sb.append(carInfo.getCarNo()).append(":非月租车,同步终止！");
                continue;
            }
            if (carInfo.getStatus().equals(CarStatusEnum.SYNC_STATUS_STOP.getCode())){
                sb.append(carInfo.getCarNo()).append(":已停用车辆,同步终止！");
                continue;
            }
            if (carInfo.getLocalStartTime() == null || carInfo.getLocalEndTime() == null){
                sb.append(carInfo.getCarNo()).append(":月卡有效期不能为空！");
                continue;
            }
            if (StringUtils.isBlank(carInfo.getOutParkId())){
                sb.append(carInfo.getCarNo()).append(":所在车场未配置线下车场！");
                continue;
            }
            ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
            rentReq.setPark_id(carInfo.getOutParkId());
            if (StringUtils.isNotBlank(carInfo.getOwnerName())){
                rentReq.setEmp_name(carInfo.getOwnerName());
            } else {
                rentReq.setEmp_name(carInfo.getMobile());
            }
            rentReq.setEmp_moblie(carInfo.getMobile());
            rentReq.setPlate_number(carInfo.getCarNo());
            rentReq.setCartypeid(carInfo.getOutCarType());
            rentReq.setCarmodelid(carInfo.getOutCarModel());
            rentReq.setBegindate(DateUtils.date2Str(carInfo.getLocalStartTime(),DateUtils.datetimeFormat));
            rentReq.setEnddate(DateUtils.date2Str(carInfo.getLocalEndTime(),DateUtils.datetimeFormat));
            Result<String> syncRes = foreignCarJGSService.saveMonthlyRent(rentReq);
            if (syncRes.isSuccess()){
                //更新同步状态
                carInfoService.updateSyncStatus(carInfo.getId());
                su.append(carInfo.getCarNo()).append(":").append(syncRes.getMessage());
            } else {
                sb.append(carInfo.getCarNo()).append(":").append(syncRes.getMessage());
            }
        }
        if (StringUtils.isNotBlank(sb.toString())){
            return Result.error(sb.toString());
        }
        return Result.ok(su.toString());
    }

    /**
     * 导出excel
     *
     * @param carInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(CarInfo carInfo) {
        // Step.1 组装查询条件
        LoginUser loginUser =  SsoUtil.getLoginUser();
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<CarInfo> pageList = carInfoService.findPage(null,carInfo);
//        for (CarInfo carRes:pageList){
//            CarOrder carOrder =  carOrderService.getEndChargeTime(carRes.getId(), CarOrderTypeEnum.ORDER_TYPE_MONTHS.getCode());
//            if (carOrder != null){
//                carRes.setEndChargeTime(carOrder.getPayTime());
//            }
//        }
//        for (CarInfo info :pageList){
             /*if(StringUtils.isNotEmpty(info.getProjectId())){
                 info.setProjectName(carInfoService.getProjectNameById(info.getProjectId()));
             }*/
             /*if(info.getIsOwner() != null && info.getIsOwner() == 1){
                 info.setIsOwnerName("业主");
                 info.setOwnerName(carInfoService.getCuserNameById(info.getOwnerId()));
             }else if(  info.getIsOwner() != null && info.getIsOwner() == 0){
                 info.setIsOwnerName("租户");
                 info.setOwnerName(carInfoService.getTentNameById(info.getOwnerId()));
             }*/
           /* if(StringUtils.isNotEmpty(info.getParkId())){
                info.setParkName(carInfoService.getParkNameById(info.getParkId()));
            }

            if(StringUtils.isNotEmpty(info.getCarPortId())){
                info.setCarPortNum(carInfoService.getCarPortNameById(info.getCarPortId()));
            }*/
//        }
        LoginUser user = SsoUtil.getLoginUser();
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "月卡车列表列表");
        mv.addObject(NormalExcelConstants.CLASS, CarInfo.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("月卡车列表列表数据", user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            int titleRow = 0;
            params.setTitleRows(titleRow);
            params.setHeadRows(titleRow++);
            params.setNeedSave(true);
            List<CarInfo> saveList = Lists.newArrayList();
            StringBuilder failureMsg = new StringBuilder();
            StringBuilder repFailureMsg = new StringBuilder();
            int failureNum = 0;
            int repFailureMsgNum = 0;
            try {
                List<CarInfo> listCarInfos = ExcelImportUtil.importExcel(file.getInputStream(), CarInfo.class, params);
                if (listCarInfos.size() <= 0){
                    return Result.error("文件内容为空，导入无效！");
                }
                String oldOb = JSON.toJSONString(listCarInfos);
                List<CarExVo> carExVos = JSON.parseArray(oldOb, CarExVo.class);
                Map<CarExVo, List<CarExVo>> collect = carExVos.stream().collect(Collectors.groupingBy(Function.identity()));
                for(Map.Entry<CarExVo, List<CarExVo>> entry : collect.entrySet()){
                    if(entry.getValue().size()>1){
                        List<CarExVo> value = entry.getValue();
                        for (CarExVo carInfo:value){
                            if (StringUtils.isNotEmpty(carInfo.getCarPortNum())){
                                if (StringUtils.isBlank(carInfo.getProjectName())){
                                    return Result.error("文件存在项目名称为空");
                                }
                                BaseProject baseProject =  carPortService.getProjectByName(carInfo.getProjectName());
                                if (null == baseProject){
                                    repFailureMsgNum++;
                                    repFailureMsg.append(carInfo.getProjectName()+"不存在");
                                }
                                if (StringUtils.isNotEmpty(carInfo.getParkName())){
                                    CarParkInfo carParkInfo = carParkInfoService.getByProjectIdAndParkName(baseProject.getId(),carInfo.getParkName());
                                    if (null== carParkInfo ){
                                        repFailureMsgNum++;
                                        repFailureMsg.append(carInfo.getProjectName()+"下没有车场"+carInfo.getParkName());
                                    }
                                    CarPort carPort = carPortService.getByParkIdAndPortNum(carParkInfo.getId(), carInfo.getCarPortNum());
                                    if (null == carPort){
                                        repFailureMsgNum++;
                                        repFailureMsg.append("<br/>第").append("行：车场没有编号为+"+carInfo.getCarPortNum()+"不能添加 ");
                                    }
                                      if (carPort.getIsAb() == 0){
                                          repFailureMsgNum++;
                                          repFailureMsg.append(carInfo.getCarPortNum()+"不是AB车位不能重复");
                                      }
                                }else {
                                    return Result.error("文件存在车场为空");
                                }
                            }
                        }
                    }
                }
                if (repFailureMsgNum > 0){
                    return Result.error(repFailureMsg.toString());
                }
                //获取项目对应配置车型和车类
                Map<String,CarConfigInfo> carProjectConfigMap = Maps.newHashMap();
                Map<String,Integer> carPortMap = new HashMap<>(); //本次导入的车位
                Map<String,Integer> carNoMap = new HashMap<>(); //本次导入的车牌号
                for (CarInfo carInfo:listCarInfos){
                    titleRow++;
                    if (StringUtils.isBlank(carInfo.getProjectName())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getCarNo()) || carInfo.getCarNo().trim().length() == 0){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入车牌号; ");
                        failureNum++;
                        continue;
                    }
                    if (!ComUtil.isPlateNumber(carInfo.getCarNo())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：车牌号码输入不合法; ");
                        failureNum++;
                        continue;
                    }
                    carInfo.setCarNo(carInfo.getCarNo().trim());
                    if ("业主".equals(carInfo.getIsOwnerName())){
                       carInfo.setIsOwner(1);
                    } else if ("租户".equals(carInfo.getIsOwnerName())){
                        carInfo.setIsOwner(0);
                    } else {
                        carInfo.setIsOwner(9); //其他
                    }
                    if (StringUtils.isBlank(carInfo.getParkName())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入车场名称; ");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getCarModelName())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入车辆类型 ");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getCarTypeName())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入车类; ");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getMobile())){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入手机号码; ");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getCarPortNum()) && (carInfo.getLocalEndTime() == null || carInfo.getLocalStartTime() == null)){
                        failureMsg.append("<br/>第").append(titleRow).append("行：请输入月租开始/结束日期; ");
                        failureNum++;
                        continue;
                    }
                    if(carInfo.getLocalEndTime() != null){
                        Calendar ca = Calendar.getInstance();
                        ca.setTime(carInfo.getLocalEndTime());
                        ca.add(Calendar.HOUR,23);
                        ca.add(Calendar.MINUTE, 59);
                        ca.add(Calendar.SECOND, 59);//获取到期日23:59:59
                        carInfo.setLocalEndTime(ca.getTime());
                    }
                    if (StringUtils.isBlank(carInfo.getCarPortNum()) && carInfo.getLocalEndTime().compareTo(carInfo.getLocalStartTime()) < 0){
                        failureMsg.append("<br/>第").append(titleRow).append("行：月租开始需小于结束日期; ");
                        failureNum++;
                        continue;
                    }
                    BaseProject baseProject =  carPortService.getProjectByName(carInfo.getProjectName());
                    if (baseProject == null){
                        failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称在系统中不存在; ");
                        failureNum++;
                        continue;
                    }
                    carInfo.setProjectId(baseProject.getId());
                    //非固定车位 && 楼栋不为空
                    if (StringUtils.isBlank(carInfo.getCarPortNum()) && StringUtils.isNotBlank(carInfo.getFloorName())){
                        BaseFloor floor =  carInfoService.getFloorByName(carInfo.getFloorName(),baseProject.getId());
                        if (floor == null){
                            failureMsg.append("<br/>第").append(titleRow).append("行：填写的楼栋名称在系统中不存在; ");
                            failureNum++;
                            continue;
                        }
                        carInfo.setFloorId(floor.getId());
                        carInfo.setFloorName(floor.getName());
                        if (StringUtils.isNotBlank(carInfo.getRoomName())){
                            while (carInfo.getRoomName().endsWith(".0")){
                                carInfo.setRoomName(carInfo.getRoomName().substring(0, carInfo.getRoomName().length() - 2));
                            }
                            BaseRoom baseRoom = new BaseRoom();
                            baseRoom.setProjectId(carInfo.getProjectId());
                            baseRoom.setFloorId(carInfo.getFloorId());
                            baseRoom.setName(carInfo.getRoomName());
                            BaseRoom room = carInfoService.getRoomByProjectFloorRoomName(baseRoom);
                            if (room == null){
                                failureMsg.append("<br/>第").append(titleRow).append("行：填写的房间名称在系统中不存在; ");
                                failureNum++;
                                continue;
                            }
                            carInfo.setRoomId(room.getId());
                            carInfo.setRoomName(room.getName());
                        }
                    }
                    CarParkInfo carParkInfo = carParkInfoService.getByProjectIdAndParkName(baseProject.getId(),carInfo.getParkName());
                    if (carParkInfo == null){
                        failureMsg.append("<br/>第").append(titleRow).append("行：填写的车场名称系统中不存在; ");
                        failureNum++;
                        continue;
                    }
                    carInfo.setParkId(carParkInfo.getId());
                    CarPort existPort = null;
                    //判断车位号是否已经存在
                    if (StringUtils.isNotBlank(carInfo.getCarPortNum())){
                        existPort =  carPortService.getByParkIdAndPortNum(carParkInfo.getId(),carInfo.getCarPortNum());
                        if (existPort != null ){
                            //if (existPort.getIsAb() == null || existPort.getIsAb() == 0){
                                CarInfo info =  carInfoService.selectByCarPortId(existPort.getId());
                                //CarPort carPort = carPortService.getByParkIdAndPortNum(carInfo.getParkId(),carInfo.getCarPortNum());
                                if(info != null && existPort.getIsAb() == 0){
                                    failureMsg.append("<br/>第").append(titleRow).append("行：车位不为AB车位，不能重复添加 ");
                                    failureNum++;
                                    continue;
                                }
                                //关联车位信息
                                carInfo.setLocalStartTime(existPort.getLocalStartTime());
                                carInfo.setLocalEndTime(existPort.getLocalEndTime());
                                carInfo.setRoomId(existPort.getRoomId());
                                carInfo.setFeeRuleId(null);
                                carInfo.setRoomName(existPort.getRoomName());
                                carInfo.setFloorId(existPort.getFloorId());
                                carInfo.setFloorName(existPort.getFloorName());
                                carInfo.setCarPortId(existPort.getId());
                            // }
                        }else{
                            failureMsg.append("<br/>第").append(titleRow).append("行：车场无当前车位编号，不能添加 ");
                            failureNum++;
                            continue;
                        }
                        if (existPort.getIsAb() == null || existPort.getIsAb() == 0){ //非AB车需要做重复校验
                            Integer mapRow = carPortMap.get(carInfo.getParkId() + "|" + carInfo.getCarPortNum());
                            if (mapRow != null){
                                failureMsg.append("<br/>第").append(titleRow).append("行：填写的车位号与").append(mapRow).append("行的车位号相同,请勿重复;");
                                failureNum++;
                                continue;
                            } else {
                                carPortMap.put(carInfo.getParkId() + "|" + carInfo.getCarPortNum(),titleRow);
                            }
                        }
                    }
                    CarConfigInfo carConfigInfo = carProjectConfigMap.get(baseProject.getId());
                    if (carConfigInfo == null){
                        carConfigInfo =  new CarConfigInfo();
                        List<CarModel> carModelList =  carModelService.findByProject(baseProject.getId());
                        List<CarType> carTypeList = carTypeService.findByProject(baseProject.getId());
                        // key: park_id + model_name  value:model_id
                        Map<String,String> carModelMap = carConfigInfo.getCarModelMap();
                        // key: park_id + type_name  value:type_id
                        Map<String,String> carTypeMap = carConfigInfo.getCarTypeMap();
                        for (CarModel carModel:carModelList){
                            carModelMap.put(carModel.getParkId() + "-" + carModel.getName(),carModel.getId());
                        }
                        for (CarType carType:carTypeList){
                            carTypeMap.put(carType.getParkId() + "-" + carType.getName(),carType.getId());
                        }
                    }
                    String carTypeId = carConfigInfo.getCarTypeMap().get(carInfo.getParkId() + "-" + carInfo.getCarTypeName());
                    if (StringUtils.isEmpty(carTypeId)){
                        failureMsg.append("<br/>第").append(titleRow).append("行：车场中未配置填写的车类");
                        failureNum++;
                        continue;
                    }
                    carInfo.setCarType(carTypeId);
                    if ("月租车".equals(carInfo.getCarTypeName()) && existPort == null){  //无车位的车辆需要加判断
                        if (StringUtils.isEmpty(carInfo.getFeeRuleName())){
                            failureMsg.append("<br/>第").append(titleRow).append("行：月租车必须填写月卡规则");
                            failureNum++;
                            continue;
                        }
                    }
                    CarFeeRule carFeeRule =  carFeeRuleService.getByParkRuleName(carParkInfo.getId(),carInfo.getFeeRuleName());
                    if (carFeeRule == null && existPort == null){
                        failureMsg.append("<br/>第").append(titleRow).append("行：车场中未配置添加的月卡规则");
                        failureNum++;
                        continue;
                    }
                    if (StringUtils.isBlank(carInfo.getCarPortNum())){
                        carInfo.setFeeRuleId(carFeeRule.getId());
                    }
                    String carModelId = carConfigInfo.getCarModelMap().get(carInfo.getParkId() + "-" + carInfo.getCarModelName());
                    if (StringUtils.isEmpty(carModelId)){
                        failureMsg.append("<br/>第").append(titleRow).append("行：车场中未配置填写的车型");
                        failureNum++;
                        continue;
                    }
                    carInfo.setCarModel(carModelId);
                    List<String> carNoList =  Arrays.asList(carInfo.getCarNo().split(","));
                    if (carNoList.size() > 0){
                        for (int i= 0 ;i<carNoList.size();i++){
                            Integer mapRow = carNoMap.get(carInfo.getParkId() + "|" + carNoList.get(i));
                            if (mapRow != null){
                                failureMsg.append("<br/>第").append(titleRow).append("行：填写的车牌与").append(mapRow).append("行的车牌相同,请勿重复;");
                                failureNum++;
                            } else {
                                CarInfo carExist = carInfoService.getByCarNo(carNoList.get(i), carParkInfo.getId());
                                if (carExist != null){
                                    failureMsg.append("<br/>第").append(titleRow).append("行：填写的车牌在系统中已存在;");
                                    failureNum++;
                                } else {
                                    CarInfo carBean = new CarInfo();
                                    BeanUtils.copyProperties(carInfo,carBean);
                                    carBean.setCarNo(carNoList.get(i));
                                    saveList.add(carBean);
                                    carNoMap.put(carInfo.getParkId() + "|" + carNoList.get(i),titleRow);
                                }
                            }
                        }
                    }
                }
                if (failureNum > 0 ){
                    return Result.error("文件导入失败:" + failureMsg.toString());
                }
                carInfoService.saveBatch(saveList);
                return Result.ok("文件导入成功！导入总数:" + saveList.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(),e);
                }
            }
        }
        return Result.ok("文件导入失败！");
    }


    @Data
    class CarConfigInfo {
        private Map<String,String> carTypeMap = Maps.newHashMap();
        private Map<String,String> carModelMap = Maps.newHashMap();
    }
}
